package com.totoro.mybatis.sharding.plugin;

import com.totoro.mybatis.sharding.domain.Page;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;
import java.util.Map;
import java.util.Properties;

/**
 *
 * Created by Niki on 2018/8/17 9:08
 */
@Intercepts({@Signature(type=StatementHandler.class, method = "prepare", args = {Connection.class})})
public class PagingPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!(invocation.getTarget() instanceof RoutingStatementHandler)) {
            return invocation.proceed();
        }

        RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();

        BoundSql boundSql = statementHandler.getBoundSql();

        Page page = null;
        Object paramObj = boundSql.getParameterObject();
        if (paramObj instanceof Page) {
            page = (Page) paramObj;
        } else if (paramObj instanceof Map) {
            for (Map.Entry<String, Object> e : ((Map<String, Object>) paramObj).entrySet()){
                if (e.getValue() instanceof Page) {
                    page = (Page) e.getValue();
                    break;
                }
            }
        }

        if (page == null) {
            return invocation.proceed();
        }

        //查找总记录
        long total = this.getTotal(invocation);
        page.setTotal(total);
        //生成分页SQL
        String pageSql = generatePageSql(boundSql.getSql(), page);
        //强制修改最终要执行的SQL
        setFieldValue(boundSql, "sql", pageSql);
        return invocation.proceed();
    }

    private void setFieldValue(BoundSql boundSql, String sql, String pageSql) {

    }

    private String generatePageSql(String sql, Page page) {
        return null;
    }

    /**
     * 获取总数
     */
    private long getTotal(Invocation invocation) {
//        RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
//        BoundSql boundSql = statementHandler.getBoundSql();
//
//        BaseStatementHandler delegate = getFieldValue(statementHandler, "delegate");
//        MappedStatement mappedStatement = getFieldValue(delegate, "mappedStatement");
//        Configuration configuration = mappedStatement.getConfiguration();
//        TypeHandlerRegistry typeHandlerRegistry = configuration.getType();
//        Object param = boundSql.getParameterObject();
//        Metaobject metaobject = ((org.apache.ibatis.session.Configuration) configuration).newMetaObject(param);
//
//        long total = 0;
//        String sql = boundSql.getSql();
//
//        String countSql = "select count(1) from (" + sql + ") as t";
//        try {
//            Connection conn = (Connection) invocation.getArgs()[0];
//            PreparedStatement ps = conn.prepareStatement(countSql);
//            int i = 1;
//            for (ParameterMapping pm : boundSql.getParameterMappings()) {
//                Object value = null;
//                String propertyName = pm.getProperty();
//                PropertyTokenizer prop = new PropertyTokenizer(propertyName);
//                if (typeHandlerRegistry.hasTypeHandler(param.getClass())) {
//                    value = param;
//                } else if (boundSql.hasAdditionalParameter(propertyName)) {
//                    value = boundSql.getAdditionalParameter(propertyName);
//                } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) {
//                    value = boundSql.getAdditionalParameter(prop.getName());
//                    if (value != null) {
//                        value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()))
//                    }
//                } else {
//                    value = ((MetaObject) metaobject).getValue(propertyName);
//                }
//
//
//
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }

        return 0;
    }

    private BaseStatementHandler getFieldValue(RoutingStatementHandler statementHandler, String delegate) {
        return null;
    }

    @Override
    public Object plugin(Object o) {
        return null;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
